<template>
  <el-dropdown @command="handleCommand">
    <span class="el-dropdown-link">
      <el-avatar :size="32" :src="currentUser?.avatar || ''" />
      <span class="username">{{ currentUser?.username || '管理员' }}</span>
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="profile">个人中心</el-dropdown-item>
        <el-dropdown-item command="settings">设置</el-dropdown-item>
        <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 获取当前用户信息
const currentUser = computed(() => authStore.currentUser)

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      // 跳转到个人中心
      router.push('/user/profile')
      break
    case 'settings':
      // 跳转到设置页面
      router.push('/config/system')
      break
    case 'logout':
      // 确认退出登录
      ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await authStore.logout()
          ElMessage.success('已退出登录')
          router.push('/auth/login')
        } catch (error) {
          ElMessage.error('退出登录失败')
        }
      }).catch(() => {
        // 取消退出
      })
      break
    default:
      break
  }
}
</script>

<style lang="scss" scoped>
.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
  
  .username {
    margin-left: 8px;
    font-size: 14px;
    color: var(--text-color-primary);
  }
}
</style>